package com.sky.service.impl;

import com.github.pagehelper.util.StringUtil;
import com.google.j2objc.annotations.AutoreleasePool;
import com.sky.dto.GoodsSalesDTO;
import com.sky.entity.Orders;
import com.sky.mapper.OrderMapper;
import com.sky.mapper.UserMapper;
import com.sky.service.ReportService;
import com.sky.service.WorkspaceService;
import com.sky.vo.*;
import org.apache.commons.lang.StringUtils;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @aothor LentDent1
 * @vision 1.0
 */
@Service
public class ReportServiceImpl implements ReportService {

    @Autowired
    private OrderMapper orderMapper;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private WorkspaceService workspaceService;
    @Override
    public TurnoverReportVO getTurnover(LocalDate begin, LocalDate end) {

        // 已有时间区间 统计表分为时间x轴和金额y轴 先获得时间轴
        // 用一个list集合来封装每一个时间点
        List<LocalDate> list = new ArrayList<>();
        list.add(begin);
//        begin.plusDays(1); 该方法用来将该日期对象的日期加一天
        // 利用while循环来逐个添加
        while (!begin.equals(end)) {
            // 判断如果开始结束日期不同 开始日期加一
            begin = begin.plusDays(1);
            // 将新日期对象添加到list集合中
            list.add(begin);
        }

        // 得到list集合 利用时间点去获得营业额对象 封装到list集合中
        List<Double> turnoverList = new ArrayList<>();
        // 循环获得list中的每个元素
        for (LocalDate localDate : list) {
            // 获取这个时间段的营业额 有开始和结束时间
            LocalDateTime beginTime = LocalDateTime.of(localDate, LocalTime.MIN);
            LocalDateTime endTime = LocalDateTime.of(localDate,LocalTime.MAX);
            // 创建一个map封装元素
            Map map = new HashMap();
            map.put("begin",beginTime);
            map.put("end",endTime);
            map.put("status", Orders.COMPLETED);
            // 调用mapper层获取该时间段的订单总金额
            Double turnover = orderMapper.sumByMap(map);
            // 判断
            turnover = turnover == null ? 0.0 : turnover;
            // 加入list集合
            turnoverList.add(turnover);
        }
        // 数据封装
        return TurnoverReportVO.builder()
                .dateList(StringUtils.join(list,","))
                .turnoverList(StringUtils.join(turnoverList,","))
                .build();
    }

    /**
     * 统计用户数量，分为：用户总数和每日新增用户数量
     * @param begin
     * @param end
     * @return
     */
    @Override
    public UserReportVO getUserStatistics(LocalDate begin, LocalDate end) {

        // 封装一个时间list集合
        List<LocalDate> dateList = new ArrayList<>();
        dateList.add(begin);

        // 循环遍历添加日期
        while (!begin.equals(end)) {
            begin = begin.plusDays(1);
            dateList.add(begin);
        }

        // 用户总数 每日新增用户总数
        List<Integer> totalUserList = new ArrayList<>();
        List<Integer> newUserList = new ArrayList<>();

        // 遍历日期集合
        for (LocalDate localDate : dateList) {
            // 获取这天的时间范围
            LocalDateTime beginTime = LocalDateTime.of(localDate, LocalTime.MIN);
            LocalDateTime endTime = LocalDateTime.of(localDate, LocalTime.MAX);
            // 新增用户数量
            Integer newUser = getUserCount(beginTime,endTime);
            Integer totalUser = getUserCount(null,endTime);

            newUserList.add(newUser);
            totalUserList.add(totalUser);
        }

        return UserReportVO.builder()
                .dateList(StringUtils.join(dateList,","))
                .newUserList(StringUtils.join(newUserList,","))
                .totalUserList(StringUtils.join(totalUserList,","))
                .build();
    }

    @Override
    public OrderReportVO orderStatistics(LocalDate begin, LocalDate end) {

        // 获取时间集合
        List<LocalDate> dateList = new ArrayList<>();
        dateList.add(begin);
        while (!begin.equals(end)) {
            begin = begin.plusDays(1);
            dateList.add(begin);
        }
        List<Integer> orderCountList = new ArrayList<>(); // 每日订单总数
        List<Integer> validOrderCountList = new ArrayList<>(); // 每日有效订单数

        // 传入时间 传入订单状态 返回count
        // select count(id) from order where order_time > ? and order_time < ?
        // 传入一个map集合 map集合要put时间：总订单数 要put时间、状态：有效订单数
        for (LocalDate localDate : dateList) {
            LocalDateTime beginTime = LocalDateTime.of(localDate, LocalTime.MIN);
            LocalDateTime endTime = LocalDateTime.of(localDate, LocalTime.MAX);

            Integer orderCount = getOrderCount(beginTime,endTime,null);
            Integer validOrderCount = getOrderCount(beginTime,endTime,Orders.COMPLETED);

            // 将数据添加到集合中
            orderCountList.add(orderCount);
            validOrderCountList.add(validOrderCount);
        }

        // 时间区间内的订单总数
        Integer orderCountSum = orderCountList.stream().reduce(Integer::sum).get();
        // 时间区间内的有效订单总数
        Integer validOrderCountSum = validOrderCountList.stream().reduce(Integer::sum).get();

        // 订单完成率
        Double orderCompletionRate = 0.0;
        if(orderCountSum != 0){
            orderCompletionRate = validOrderCountSum.doubleValue() / validOrderCountSum;
        }

        return OrderReportVO.builder()
                .dateList(StringUtils.join(dateList,","))
                .orderCompletionRate(orderCompletionRate)
                .orderCountList(StringUtils.join(orderCountList,","))
                .totalOrderCount(orderCountSum)
                .validOrderCount(validOrderCountSum)
                .validOrderCountList(StringUtils.join(validOrderCountList,","))
                .build();
    }

    public SalesTop10ReportVO getSalesTop10(LocalDate begin, LocalDate end){
        LocalDateTime beginTime = LocalDateTime.of(begin, LocalTime.MIN);
        LocalDateTime endTime = LocalDateTime.of(end, LocalTime.MAX);
        List<GoodsSalesDTO> goodsSalesDTOList = orderMapper.getSalesTop10(beginTime, endTime);

        String nameList = StringUtils.join(goodsSalesDTOList.stream().map(GoodsSalesDTO::getName).collect(Collectors.toList()),",");
        String numberList = StringUtils.join(goodsSalesDTOList.stream().map(GoodsSalesDTO::getNumber).collect(Collectors.toList()),",");

        return SalesTop10ReportVO.builder()
                .nameList(nameList)
                .numberList(numberList)
                .build();
    }

    @Override
    public void exportBusinessData(HttpServletResponse response) {
        // 获得未来最近30天的开始结束时间点
        LocalDate begin = LocalDate.now().minusDays(30);
        LocalDate end = LocalDate.now().minusDays(1);
        // 获取表格对应的数据封装对象 begin的0点到end的23.5999999点
        BusinessDataVO businessData = workspaceService.getBusinessData(LocalDateTime.of(begin, LocalTime.MIN), LocalDateTime.of(end, LocalTime.MAX));
        // 创建输入流 也就是给excel对象的传入值提供对象
        InputStream inputStream = this.getClass().getClassLoader().getResourceAsStream("template/运营数据报表模板.xlsx");
        try {
            // 基于模板创建excel对象
            XSSFWorkbook excel = new XSSFWorkbook(inputStream);
            // 获得sheet页
            XSSFSheet sheet = excel.getSheet("Sheet1");
            // 填充时间
            sheet.getRow(1).getCell(1).setCellValue(begin + "至" + end);
            // 填充概览数据
            // 获得行
            XSSFRow row = sheet.getRow(3);
            // 根据对应格填充数据
            row.getCell(2).setCellValue(businessData.getTurnover());
            row.getCell(4).setCellValue(businessData.getOrderCompletionRate());
            row.getCell(6).setCellValue(businessData.getNewUsers());
            // 获得行
            row = sheet.getRow(4);
            // 根据对应表格进行填充
            row.getCell(2).setCellValue(businessData.getValidOrderCount());
            row.getCell(4).setCellValue(businessData.getUnitPrice());
            for ( int i = 0; i < 30; i++) {
                LocalDate date = begin.plusDays(1);
                //准备明细数据
                    businessData = workspaceService.getBusinessData(LocalDateTime.of(date,LocalTime.MIN), LocalDateTime.of(date, LocalTime.MAX));
                row = sheet.getRow(7 + i);
                row.getCell(1).setCellValue(date.toString());
                row.getCell(2).setCellValue(businessData.getTurnover());
                row.getCell(3).setCellValue(businessData.getValidOrderCount());
                row.getCell(4).setCellValue(businessData.getOrderCompletionRate());
                row.getCell(5).setCellValue(businessData.getUnitPrice());
                row.getCell(6).setCellValue(businessData.getNewUsers());
            }

            // 通过输出流将文件下载到浏览器中
            ServletOutputStream out = response.getOutputStream();
            excel.write(out);
            // 关闭资源
            out.flush();
            out.close();
            excel.close();

        } catch (IOException e) {
            throw new RuntimeException(e);
        }

    }

    /**
     * 通过时间获取用户数量
     * @param begin
     * @param end
     * @return
     */
    public Integer getUserCount (LocalDateTime begin, LocalDateTime end) {
        Map map = new HashMap();
        map.put("begin", begin);
        map.put("end",end);

        return userMapper.countByMap(map);
    }

    /**
     * 通过时间获取订单数量
     * @param begin
     * @param end
     * @param status
     * @return
     */
    public Integer getOrderCount (LocalDateTime begin, LocalDateTime end, Integer status) {
        Map map = new HashMap();
        map.put("begin", begin);
        map.put("end",end);
        map.put("status",status);

        return orderMapper.countByMap(map);
    }


}
